//index.js
import {
  userLogin,
  queryUserInfo
} from "../../http/api.js"
//获取应用实例
const app = getApp()
Page({
  data: {
    userInfo: {},
    userPhone: '',
    hashUrl: '' //路径参数
  },
  onShow: function() {

  },
  onLoad: function (options) {
    if (options && options.hashUrl) {
      this.setData({
        hashUrl: options.hashUrl
      })
    }
  },
  //获取用户授权&&获取用户code
  getUserInfo: function(e) {
    wx.login({
      success: res => {
        let code = res.code;
        console.log(`code: ${code}`);
        let encryptedData =  e.detail.encryptedData;
        let iv =  e.detail.iv;
        let rawData =  e.detail.rawData;
        let signature =  e.detail.signature;
        userLogin({
          code: code,
          encryptedData:encryptedData,
          iv:iv,
          rawData:rawData,
          signature:signature
        }).then(res => {
          if (res.code == 200) {
            let openId = res.data.openId;
            let token =  res.data.token
            wx.setStorageSync('userState',{openId,token} );
            wx.switchTab({
              url: '/pages/home/index',
            })
          }
        });
      }
    });
  },
  //取消授权返回首页
  goHome: function(e) {
    wx.switchTab({
      url: '/pages/home/index'
    })
  },
  //是否绑定手机号处理
  handBindPhone(openId) {
    let that = this;
    queryUserInfo({
      openId: openId
    }).then(res => {
      if (res.data.code == '0000') {
        if (!res.data.data.phoneNo) {
          //缓存用户时候没有关联手机
          wx.setStorage({
            key: 'hasPhoneState',
            data: false
          });
          if (that.data.hashUrl) {
            wx.redirectTo({
              url: '/pages/mine/bind/index?hashUrl=' + that.data.hashUrl
            })
            return
          }else{
            wx.navigateTo({
              url: '/pages/mine/bind/index'
            })
          }
        } else {
          //缓存用户时候关联了手机
          wx.setStorage({
            key: 'hasPhoneState',
            data: true
          })
           if (that.data.hashUrl) {
             let urlArr = that.data.hashUrl.split("#")
             let option = ''
             if (urlArr[1]) {
               let params = JSON.parse(urlArr[1])
               for (let p in params) {
                 option = option + p + '=' + params[p] + '&'
               }
             }
             if (urlArr[0] == '/pages/mine/index' || urlArr[0] == '/pages/order/index') {
               wx.switchTab({
                 url: `${urlArr[0]}?${option}`
               })
             }else{
              wx.redirectTo({
                url: `${urlArr[0]}?${option}`
              })
              return;
             }
           }
        }
      }
    });
  }
})